package fr.alesia.capitale.dao.txt;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Logger;

import fr.alesia.capitale.Capitales;
import fr.alesia.capitale.bean.Pays;
import fr.alesia.capitale.dao.PaysDao;
import fr.alesia.capitale.factory.BeanFactory;

public class PaysDaoTxt implements PaysDao{

	private static PaysDao instance = null;
	private Map<String, Pays> pays;
	
	private PaysDaoTxt(){
		
		this.load(Capitales.PAYS_TXT);
	}
	
	public static PaysDao getInstance(){
		
		if(instance == null){
			instance = new PaysDaoTxt();
		}
		return instance;
	}

	public Pays get(String pays) {
		
		return this.pays.get(pays);
	}

	public SortedSet<Pays> getAll() {
		
		return new TreeSet<Pays>(pays.values());
	}
	
	private void load(String path){
		
		this.pays = new HashMap<String, Pays>(200);
		try{
			InputStream stream 		= new FileInputStream(path);
			Reader reader 			= new InputStreamReader(stream);
			BufferedReader buffer 	= new BufferedReader(reader);
			
			String line = null;
			while((line = buffer.readLine()) != null){
				
				String[] tokens = line.split("%");
				if(tokens.length == 3){
					
					String nom = tokens[0];
					String capitale = tokens[1];
					Integer niveau = Integer.valueOf(tokens[2]);
					
					Pays pays = BeanFactory.create(nom, capitale, niveau); 
					this.pays.put(nom, pays);
					
					nom = null;
					capitale = null;
					niveau = null;
					pays = null;
				}
				tokens = null;
			}
			
			buffer.close();
			reader.close();
			stream.close();
			
			buffer = null;
			reader = null;
			stream = null;
			
		}
		catch(IOException e){
			
			Logger.getAnonymousLogger().severe(e.getMessage());
			e.printStackTrace();
		}
	}
}
